<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="brandFilterSelectValue" placeholder="品牌" filterable clearable multiple collapse-tags class="filter-item" style="width: 200px"
        @change = "handleBrandFilterSelect">
        <el-option v-for="item in brandListData" :key="item.id" :label="item.name+'('+item.id+')'" :value="item.id">
        </el-option>
      </el-select>
      <TreeSelect v-model="categoryFilterSelectValue" placeholder="品类" style="width:200px" show-checkbox filterable clearable defaultExpandAll :expand-on-click-node="false"
        :data="categoryTreeData"
        :props = "{ value: 'id',label: 'name',children: 'children' }"
        @change = "handleCategoryFilterSelectChange($event)"/>
      <el-select v-model="listQuery.isActive" placeholder="是否启用" clearable class="filter-item" style="width: 130px">
        <el-option :key="true" :label="'是'" :value="true" />
        <el-option :key="false" :label="'否'" :value="false" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="100" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" sortable="custom" align="left" :class-name="getSortClass('name')">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="型号" prop="model" sortable="custom" align="left" :class-name="getSortClass('model')">
        <template slot-scope="{row}">
          <span>{{ row.model }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌" prop="brandId" sortable="custom" align="center" width="120px" :class-name="getSortClass('brandId')">
        <template slot-scope="{row}">
          <el-tag>{{ row.brandId | brandFilter }} ({{ row.brandId }})</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="品类" prop="categoryId" sortable="custom" align="center" width="120px" :class-name="getSortClass('categoryId')">
        <template slot-scope="{row}">
          <el-tag>{{ row.categoryId | categoryFilter }} ({{ row.categoryId }})</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否可用" prop="isActive" sortable="custom" align="center" width="150px" :class-name="getSortClass('isActive')">
        <template slot-scope="{row}">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdTime" sortable="custom" align="center" width="150px" :class-name="getSortClass('createdTime')">
        <template slot-scope="{row}">
          <span>{{ row.createdTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="temp.model" />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="temp.brandId" class="filter-item" placeholder="请选择">
            <el-option v-for="item in brandListData" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="品类" prop="categoryId">
          <TreeSelect v-model="temp.categoryId" placeholder="品类" filterable clearable defaultExpandAll :expand-on-click-node="false"
            :data="categoryTreeData"
            :props = "{ value: 'id',label: 'name',children: 'children' }"/>
        </el-form-item>
        <el-form-item label="是否可用" prop="isActive">
          <el-switch v-model="temp.isActive" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" :autosize="{ minRows: 4, maxRows: 8}" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Create, Update, Delete, Get, GetPagedList } from '@/api/product'
import { GetList as GetBrandList } from '@/api/brand'
import { GetTree as GetCategoryTree} from '@/api/category'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import TreeSelect from '@/components/TreeSelect' // secondary package based on el-pagination
let that
export default {
  name: 'Product',
  components: { Pagination,TreeSelect },
  directives: { waves },
  filters: {
    brandFilter(id) {
      return that.brandListData.find(item => item.id == id)?.name
    },
    categoryFilter(id) {
      return that.categoryListData.find(item => item.id == id)?.name
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      categoryTreeData: null,
      categoryListData: [],
      categoryFilterSelectValue:null,
      brandListData: [],
      brandFilterSelectValue:null,
      downloadLoading: false,
      pvData: [],
      dialogPvVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        name: [{ required: true, message: '名称必填', trigger: 'change' }],
        model: [{ required: true, message: '型号必填', trigger: 'change' }],
        brandId: [{ required: true, message: '品牌必选', trigger: 'change' }],
        categoryId: [{ required: true, message: '品类必选', trigger: 'change' }],
        isActive: [{ required: true, message: '是否可用必选', trigger: 'change' }]
      },
      temp: {
        id: undefined,
        name: null,
        model: null,
        brandId: null,
        categoryId: null,
        description: null,
        isActive: false
      },
      listQuery: {
        pageIndex: 1,
        pageSize: 10,
        sorting: null,
        id: null,
        name: null,
        brandIds: null,
        categoryIds: null,
        isActive: null
      },
      pagedList: {
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        items: null
      },
      defaultProps:{
        value: 'id',
        label: 'name',
        children: 'children',
      }
    }
  },
  beforeCreate () {
	  that = this
  },
  created() {
    this.getBrandList()
    this.getCategoryTree()
    this.getList()
  },
  methods: {
    getBrandList() {
      GetBrandList({sorting:'id ascending'}).then(response => {
        let data = response.data
        if(data){
          data.forEach(item => {
            this.brandListData.push({ id: item.id, name: item.name })
          });
        }
      })
    },
    getCategoryTree() {
      GetCategoryTree().then(response => {
        let data = response.data.children
        if(data){ 
            this.categoryTreeData = data
            this.categoryListData = this.treeToList(this.categoryTreeData,"children")
        }
      })
    },
    getList() {
      this.listLoading = true
      GetPagedList(this.listQuery).then(response => {
        this.pagedList = response.data;
        this.list = this.pagedList.items
        this.total = this.pagedList.totalCount
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      })
    },
    handleFilter() {
      this.listQuery.pageIndex = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: null,
        model: null,
        brandId: null,
        categoryId: null,
        description: null,
        isActive: false
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Create(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
          })
        }
      })
    },
    handleUpdate(row) {
      this.listLoading = true
      Get({id:row.id}).then(response => {
        Object.keys(this.temp).forEach((key) => {
          this.temp[key] = response.data[key]
        })
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    updateData() {
      console.log(this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          Update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.listLoading = true
      Delete({id:row.id}).then(response => {
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.handleFilter()
      })
    },
    sortChange(data) {
      const { prop, order } = data 
      if(prop && order){
        this.listQuery.sorting = prop + (order === 'ascending' ? ' ascending' : ' descending')
      }
      else {
        this.listQuery.sorting = null
      }
      this.handleFilter()
    },
    getSortClass: function(key) {
      if(this.listQuery.sorting){
        const items = this.listQuery.sorting.split(' ')
        if(items[0] == key){
          return items[1]
        }
      }
      return null
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '名称', '型号', '品牌', '品类', '是否可用', '创建时间']
        const filterVal = ['id', 'name', 'model', 'brandId', 'categoryId', 'isActive', 'createdTime']
        const data = this.list.map(v => filterVal.map(j => {
          if (j === 'brandId') { 
            return this.brandListData.find(item => item.id == v[j])?.name
          }
          else if (j === 'categoryId') {
            return this.categoryListData.find(item => item.id == v[j])?.name
          }
          else if (j === 'isActive') {
            return v[j] === true ? '是' : '否'
          }
          else {
            return v[j]
          }
        }))
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'product-list'
        })
        this.downloadLoading = false
      })
    }, 
    handleBrandFilterSelect(node){
      this.listQuery.brandIds = null
      if(node){
        this.listQuery.brandIds = node.join(',')
      }
    },
    handleCategoryFilterSelectChange(data){
      this.listQuery.categoryIds = null
      if(data){ 
        // 多选
        if(data.multiple){
          if(this.categoryFilterSelectValue){
            this.listQuery.categoryIds = this.categoryFilterSelectValue.join(',')
          }
        }else{
          if(data.data){ 
            let values = data.id
            if(data.children){
              let dataArray = []
              dataArray.push(data.data)
              let items = this.treeToList(dataArray,"children")
              if(items){
                values = items.map((item,index)=>{
                  return item.id
                }).join(',')
              }
            }
            this.listQuery.categoryIds = values
          }
        }
      }
    },
     
    treeToList(arrs,childs,attrArr){
      let attrList = []
      if(!Array.isArray(arrs) && !arrs.length) {
        return []
      }
      if(typeof childs !== 'string') {
        return []
      }
      if(!Array.isArray(attrArr) || Array.isArray(attrArr) && !attrArr.length) {
        attrList = Object.keys(arrs[0])
        attrList.splice(attrList.indexOf(childs), 1)
      }
      else{
        attrList = attrArr;
      }
      let list = []
      const getObj = (arr)=> {
        arr.forEach(row => {
          let obj = {}
          attrList.forEach(item=> {
            obj[item] = row[item];
          })
          list.push(obj)
          if(row[childs]){
            getObj(row[childs])
          }
        })
        return list
      }
      return getObj(arrs)
    }
  }
}
</script>
